﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Sustainalytics.ClientDW.Entities;
using System;
using System.Linq;

namespace Sustainalytics.ClientDW.DataAccessLayer.Tests
{
    [TestClass]
    public class ClientDWMasterRepositoryTests
    {
        private const string MongoDbConnectionString = "mongodb://localhost:27017";
        private IClientDWMasterRepository _repository;
        private IMongoDatabase _database;

        [TestInitialize]
        public void Initialize()
        {
            _repository = ClientDWMasterRepository.GetInstance(MongoDbConnectionString);

            var url = MongoUrl.Create(string.Format("{0}/{1}", MongoDbConnectionString, "ClientDWMaster"));

            if (string.IsNullOrWhiteSpace(url.DatabaseName))
                throw new ArgumentException("No database specified in the connection string!");

            var client = new MongoClient(url);

            _database = client.GetDatabase(url.DatabaseName);
        }

        [TestCleanup]
        public void Cleanup()
        {
            _repository.Cleanup();
        }

        [TestMethod]
        public void AddNewEntryInSyncLogTest()
        {
            var syncLog = _repository.AddNewEntryInSyncLog(false);

            Assert.IsTrue(syncLog.Status == LastSessionStatus.Running, "Sync status is different than the expected one!");

            syncLog.DatabaseGroup = DatabaseGroup.A;
            syncLog.Status = LastSessionStatus.Finished;
            syncLog.TimeSync = TimeSpan.FromSeconds(10).ToString();
            _repository.UpdateSyncLog(syncLog);

            var collection = _database.GetCollection<SyncLog>(typeof(SyncLog).Name).AsQueryable();

            var dbSyncLog = collection.FirstOrDefault();

            Assert.IsNotNull(dbSyncLog != null && dbSyncLog.TimeEnd != null, "The last sync date returned is null!");
            Assert.IsNotNull(dbSyncLog != null && dbSyncLog.DatabaseGroup == DatabaseGroup.A, "The database group is different than the expected one!");
            Assert.IsTrue(syncLog.Status == LastSessionStatus.Finished, "Sync status is different than the expected one!");
        }

        [TestMethod]
        public void GetLastSyncDate()
        {
            var syncLog = _repository.AddNewEntryInSyncLog(false);
            syncLog.Status = LastSessionStatus.Finished;
            _repository.UpdateSyncLog(syncLog);

            syncLog = _repository.GetLastSync(false);

            Assert.IsNotNull(syncLog.TimeEnd != null, "The last sync date returned is null!");
        }
    }
}
